import envConf from '@/conf/env.conf.js';
import store from 'store'
// 请求方法
export const METHODS = {
    GET: 'GET',
    POST: 'POST',
    DELETE: 'DELETE',
    PUT: 'PUT'
};

export default function request(params) {
    uni.showLoading({
        title: '加载中',
    });
    for (let i in params.data) {
    	if (params.data[i] === "" || params.data[i] === undefined || params.data[i] === "undefined" || params.data[i] === null || params.data[
    			i] === "null") {
    		delete params.data[i];
    	}
    }
    let token = uni.getStorageSync('token');
    store.commit('login', !!token);
    uni.setStorageSync('login', !!token);
    let url = params.url;
    if (!params.isAbsUrl) {
        url = envConf.tuiDomain + url;
    }
    let name = '';
    if (params.params) {
        for (let type in params.params) {
            name += `${type}=${params.params[type]}&`
        }
        name = '?' + name.substr(0, name.length - 1)
    }
    const requestTask = uni.request({
        url: url + name,
        method: (params.method || METHODS.GET).toUpperCase(),
        data: params.data,
        success: res => {
            uni.hideLoading();
            let strCode = res.statusCode.toString();
            let firstCode = strCode.substring(0, 1);
            // 没有访问权限
            if (res.statusCode === 402) {
                uni.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000,
                });
                store.commit('login', false);
                uni.setStorageSync('login', false);
                return;
            } else if (firstCode === '4') {
                uni.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000,
                });
                return;
            } else if (res.statusCode !== 200 && res.statusCode !== 304) {
                // 服务端明确错误
                uni.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000,
                });
                return;
            }
            if (params.success) {
                params.success(res.data);
            }
        },
        fail: res => {
            uni.hideLoading();
            if (params.fail) {
                params.fail(res);
            } else {
                uni.showToast({
                    title: '服务器请求失败：' + JSON.stringify(res),
                    icon: 'none',
                    duration: 2000,
                });
            }
        },
        complete: res => {
            if (params.complete) {
                params.complete(res);
            }
        },
        header: {
            deviceType: 'xcx',
            Cookie: `token=${uni.getStorageSync('token')}`,
        },
    });
    // 调用requestTask.abort()可中断请求任务
    return requestTask;
};
